﻿using InvestmentIntelligence.TradingData.Adapters.Mus.Models;
using InvestmentIntelligence.TradingData.DataProcessing.DataResolvers;
using System.Collections.Generic;

namespace InvestmentIntelligence.TradingData.Adapters.Mus.MarketIndicators.TimeLineBuilders
{
    public class SimpleMovingAverageTimelineBuilder :ITimelineBuilder
    {
        private readonly int _window;

        public SimpleMovingAverageTimelineBuilder(int window)
        {
            _window = window;
        }
        
        public List<Timeline> Build(List<TimeSerieInfo> timeSeries)
        {
            var result = new List<Timeline>();
            if (timeSeries.Count < _window) return result;

            var queue = new Queue<TimeSerieInfo>();
            var sum = 0m;
            for (var i = 0; i < timeSeries.Count; i++)
            {
                var timeSerie = timeSeries[i];
                sum += timeSerie.ClosePrice;
                queue.Enqueue(timeSeries[i]);

                if (i < _window - 1) continue;

                result.Add(new Timeline
                {
                    Date = timeSerie.Date,
                    Value = sum / _window,
                });

                var itemToRemove = queue.Dequeue();
                sum -= itemToRemove.ClosePrice;
            }

            return result;
        }
    }
}
